package com.cat.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import static com.cat.util.ServletUtils.showError;


/**
 * @author :HYC  email: kobe524348@gmail.com
 * @program : HYC_CatRecruit
 * @name : StudentFilter
 * @description : a filter to check the request
 * @create : 2019-03-26 20:00
 */
@WebFilter("/StudentServlet")
public class StudentFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        HttpSession sess = req.getSession();
        String method = req.getParameter("method");
        System.out.println("com.cat.filter.StudentFilter : method is  "+method);

        if ("myinfo".equalsIgnoreCase(method)) {
            //检查是否登陆
            if (sess.getAttribute("login") == null) {
                System.out.println("com.cat.filter.StudentFilter : no user login ");
                //重定向到登陆页面
                showError(req,res,"操作失败：当前没有登陆用户","解决方案：请检查检查您的登陆状态，请先登陆您的账户再进行此操作");
                res.sendRedirect("login.jsp");
                return;
            }
        } else if ("login".equalsIgnoreCase(method)) {
            if (sess.getAttribute("login") == null) {
                //重定向到登陆页面
                res.sendRedirect("login.jsp");
                return;
            } else {
                //已经登陆，转发到个人信息页
                req.setAttribute("login", sess.getAttribute("login"));
                req.setAttribute("admin", sess.getAttribute("admin"));
                req.getRequestDispatcher("myinfo.jsp").forward(req, res);
                return;
            }
        }else if ("register".equalsIgnoreCase(method) || "join us".equalsIgnoreCase(method)) {
            //重定向到注册页面
            res.sendRedirect("register.jsp");
            return;
        }else if("修改".equalsIgnoreCase(method)||"取消".equalsIgnoreCase(method)){
            req.getRequestDispatcher("AdminServlet").forward(req,res);
            return;
        }
        System.out.println("com.cat.filter.StudentFilter : pass ! ");
        filterChain.doFilter(req, res);
    }
}